package net.pinnoocle.playcommon.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import java.io.*;
import java.net.URL;

/**
 * @author ye
 * @Description
 * @create 2021-11-24 16:14
 */
@Slf4j
public class DownloadImageLocal {

    /**
     * 下载网络图到本地
     * @param imageUrl
     * @param newImageName
     * @return
     */
    public static String downloadPicture(String imageUrl, String newImageName,String uploadPath,String mapUrl) {
        URL url = null;
        try {
            File file = new File(uploadPath+newImageName);
            if (file.exists() && file.isFile()) {
                return mapUrl + newImageName;
            }
            url = new URL(imageUrl);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());
            FileOutputStream fileOutputStream = new FileOutputStream(new File(uploadPath+newImageName));
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int length;

            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            byte[] context=output.toByteArray();
            fileOutputStream.write(output.toByteArray());
            dataInputStream.close();
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return mapUrl + newImageName;
    }
}
